package com.yigo.prc.app.service;

import com.yigo.framework.http.BException;
import com.yigo.prc.api.category.command.CreateCategoryCmd;
import com.yigo.prc.api.constant.PrcCodeEnum;
import com.yigo.prc.app.assembler.CategoryDTO2DmoAssembler;
import com.yigo.prc.domain.category.entity.PrcCategory;
import com.yigo.prc.domain.category.repo.PrcCategoryRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author chenzl
 */
@Slf4j
@Service
public class PrcCategoryAppService {
    @Resource
    private PrcCategoryRepo prcCategoryRepo;

    @Transactional(rollbackFor = Exception.class)
    public void createCategory(CreateCategoryCmd cmd) {
        Long count = prcCategoryRepo.countByPidAndName(cmd.getPid(), cmd.getCategoryName());
        if (count > 0) {
            throw new BException(PrcCodeEnum.CREATE_CATEGORY_EXISTS, cmd.getPid(), cmd.getCategoryName());
        }
        PrcCategory prcBrand = CategoryDTO2DmoAssembler.INSTANCE.toDmo(cmd);
        prcCategoryRepo.save(prcBrand);
    }
}
